package com.hongsen.cn.rest;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hongsen.cn.Utils.LogUtil;
import com.hongsen.cn.application.DayAndMonthApplication;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;


public class HttpManager {
    private Logger logger = (Logger) LoggerFactory.getLogger(HttpManager.class);
    private String baseUrl;
    private static RestApi restApi = null;
    private volatile static HttpManager mInstance = null;

    public static HttpManager getSingleton() {
        if (mInstance == null) {
            synchronized (HttpManager.class) {
                mInstance = new HttpManager();
            }
        }
        return mInstance;
    }

    public HttpManager() {

    }

    public void initHttp(String urlPath) {
        baseUrl = urlPath;
        if (StringUtils.isBlank(baseUrl)){
            baseUrl = DayAndMonthApplication.getInstance().getCenterIp();
        }

        LogUtil.e("baseUrl-->"+ baseUrl);

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                .addNetworkInterceptor(new TokenInterceptor())
                .connectTimeout(300, TimeUnit.SECONDS).
                readTimeout(300, TimeUnit.SECONDS).
                writeTimeout(300, TimeUnit.SECONDS)
                .build();
        JacksonConverterFactory factory = JacksonConverterFactory.create(mapper);
        try {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(factory)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 使用RxJava作为回调适配器
                    .client(okHttpClient)
                    .build();
            restApi = retrofit.create(RestApi.class);
        } catch (Exception e) {
            LogUtil.e("retrofit初始化错误");
        }
    }

    public RestApi getRestApi() {
        return restApi;
    }
}
